# -*- coding: utf-8 -*-
#! /usr/bin/env python

from PySide import QtCore, QtGui, QtWebKit
from PySide.QtCore import SIGNAL, QSettings, QSize, QPoint, QAbstractListModel, QModelIndex, Qt
from PySide.QtWebKit import QWebSettings
import logging, time, os
from pprint import pprint
from datetime import datetime

from ui_auto import Ui_MainWindow
from worker import QWorker, unescape
from config import *
from utils import *
from fer_fetcher import Fer

logger = logging.getLogger('fer_fetcher')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('fer_fetcher.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)        


# t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle
# f_id, f_title, f_answers, f_bluetime, f_lastauthor, f_threads, f_parentid
# t_id, t_title, t_bluetime, t_open1, t_open2, t_answers, t_author, t_author_id, t_lastauthor, t_lastauthor_id, t_undertitle

webSettings = QWebSettings.globalSettings()
webSettings.setFontFamily(QWebSettings.FixedFont, FixedFont)
webSettings.setFontFamily(QWebSettings.StandardFont, FixedFont)
        
_initial_dict = {'item_id': 0,
                       'title': '',
                       'parent_id': 0,
                       'threads': 0,
                       'answers': 0,
                       'checked': 0,
                       'subscribed': 0,
                       'timestamp': 0,
                       }

class Item(object): 
    #def __init__(self, item_id = 0, title = '', parent_id = 0, ):
    def __init__(self, _dict):
        self.__dict__.update(_initial_dict)
        self.__dict__.update(_dict)

    def __repr__(self):
        return u'<%s:%s>' % (self.item_id, self.parent_id)
        
    def __unicode__(self):
        return u'<%s:%s: %s>' % (self.item_id, self.parent_id, self.title)
        
    def _data(self):
        t = [(0, self.title)]
        if self.threads:
            t += (1, str(self.threads)),
        if self.answers:
            t += (2, str(self.answers)),
        if self.timestamp:
            t += (3, str(self.timestamp)),
        return t


class CountDown(QtCore.QThread): 
    
    def __init__(self, parent = None, interval = 0): 
        QtCore.QThread.__init__(self, parent) 
        self.interval = interval
        self.timer = QtCore.QTimer(self) 
        self.connect(self.timer, SIGNAL("timeout()"), self.update) 
                     
    def run(self):
        self.timer.start(1000) 

    def set_interval(self, interval):
        self.interval = self.i = interval
        self.emit(SIGNAL('update_countdown(int)'), self.i / 1000)

    def update(self): 
        self.emit(SIGNAL('update_countdown(int)'), self.i / 1000)
        if self.i == 0:
            self.i = self.interval
            #self.timer.stop()
        self.i -= 1000
        
        
class TreeWidgetItem(QtGui.QTreeWidgetItem):
    def __init__(self, parent):
        QtGui.QTreeWidgetItem.__init__(self, parent)
        self.item_id = 0
        self.parent_id = 0

    
class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, icon, parent = None, menu = None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        if not menu:
            menu = QtGui.QMenu(parent)
            exitAction = menu.addAction("Exit")
        self.setContextMenu(menu)
        

class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        logger.info('creating an instance of QtGui.QMainWindow')
        self.ul_threads = {}
        self.open_threads = {}
        self.subscribe_widgets = {}
        self.forum = Fer()
        self.forum.authorize()
        
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.centralwidget.setLayout(self.ui.gridLayout)
        self.ui.tab.setLayout(self.ui.gridLayout_7)
        self.ui.tab_2.setLayout(self.ui.gridLayout_2)
        self.radio_button_group = QtGui.QButtonGroup(self.ui.update_target)
        for i, button in enumerate((self.ui.get_all_rb, self.ui.get_selected_rb, self.ui.get_unselected_rb)):
            self.radio_button_group.addButton(button)
            self.radio_button_group.setId(button, i)
        self.radio_button_group.buttonClicked.connect(self.radio_activateInput)
        
        self.read_settings()
        self.create_context_menu()
        
        self.ui.check_on_startup_cb.stateChanged.connect(self.write_settings)
        self.ui.reload_interval_sb.valueChanged.connect(self.change_interval)
        self.ui.reload_posts_interval_sb.valueChanged.connect(self.change_posts_interval)
        self.ui.reload_interval_subscription_sb.valueChanged.connect(self.change_subscribed_update_interval)
        self.ui.hide_to_tray_cb.stateChanged.connect(self.write_settings)
        QtCore.QObject.connect(self.ui.tab_widget, SIGNAL('tabCloseRequested(int)'), self.close_tab)
        self.ui.subscribe_listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.subscribe_listWidget.customContextMenuRequested.connect(self.subscribe_context_menu)
        self.ui.subscribe_listWidget.currentItemChanged.connect(self.view_subscribed_thread)
        self.ui.subscribe_listWidget11.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.ui.subscribe_listWidget11.customContextMenuRequested.connect(self.subscribe_context_menu)
        self.ui.tree_widget.customContextMenuRequested.connect(self.tree_context_menu)
        self.ui.tree_widget.setColumnWidth(0, 400)
        self.ui.tree_widget.resizeEvent = self.on_tree_resize
        self.ui.tree_widget.itemChanged.connect(self.on_tree_widget_item_changed)
        self.ui.tree_widget.doubleClicked.connect(self.open_thread)
        self.ui.get_forums_button.clicked.connect(self.update_threads)
        self.ui.get_posts_button.clicked.connect(self.update_posts)
        self.ui.update_subscribed_button.clicked.connect(self.update_subscribed)
        #self.connect(self.ui.pushButton_2, SIGNAL('clicked()'), self.open_thread)
        self.ui.action.triggered.connect(QtGui.qApp.quit)
        self.trayIcon = SystemTrayIcon(QtGui.QIcon("icon.ico"), self, self.ui.menu)
        self.trayIcon.show()
        self.trayIcon.activated.connect(self.__icon_activated)

        self.init_tree_widget()
        self.init_subscribe_widget()
        if RESTORE_OPENED_THREADS and self.open_threads_list:
            for thread_id in self.open_threads_list:
                self.open_thread(thread_id)
        
        if int(self.settings.value("MainWindow/check_on_startup_cb", 0)):
            self.update_threads()
        self.update_interval = int(self.settings.value("MainWindow/reload_interval_sb", 0))
        self.forums_timer = QtCore.QTimer()
        self.forums_timer.timeout.connect(self.update_threads) 
        self.lcd_timer = CountDown()
        self.ui.lcd_number_forums.connect(self.lcd_timer, SIGNAL('update_countdown(int)'), self.ui.lcd_number_forums, QtCore.SLOT('display(int)'))
        if self.update_interval:
            self.forums_timer.start(1000 * 60 * self.update_interval)        
            self.lcd_timer.set_interval(1000 * 60 * self.update_interval)
            self.lcd_timer.start()        
            
        self.update_interval = int(self.settings.value("MainWindow/reload_posts_interval_sb", 0))
        self.posts_timer = QtCore.QTimer()
        self.posts_timer.timeout.connect(self.update_posts) 
        self.lcd_posts_timer = CountDown()
        self.ui.lcd_number_posts.connect(self.lcd_posts_timer, SIGNAL('update_countdown(int)'), self.ui.lcd_number_posts, QtCore.SLOT('display(int)'))
        if self.update_interval:
            self.posts_timer.start(1000 * 60 * self.update_interval)        
            self.lcd_posts_timer.set_interval(1000 * 60 * self.update_interval)
            self.lcd_posts_timer.start()        
            
        self.update_interval = int(self.settings.value("MainWindow/reload_interval_subscription_sb", 0))
        self.subscribed_timer = QtCore.QTimer()
        self.subscribed_timer.timeout.connect(self.update_subscribed) 
        self.lcd_subscribed_timer = CountDown()
        self.ui.lcd_number_subscription.connect(self.lcd_subscribed_timer, SIGNAL('update_countdown(int)'), self.ui.lcd_number_subscription, QtCore.SLOT('display(int)'))
        if self.update_interval:
            self.subscribed_timer.start(1000 * 60 * self.update_interval)        
            self.lcd_subscribed_timer.set_interval(1000 * 60 * self.update_interval)
            self.lcd_subscribed_timer.start()        
            
    def radio_activateInput(self, button):
        self.update_target = self.radio_button_group.checkedId()
        self.settings.setValue("MainWindow/update_target", self.radio_button_group.checkedId())
        
    def on_tree_resize(self, event):
        self.ui.tree_widget.setColumnWidth(0, self.ui.tree_widget.width() - 410)
        self.ui.tree_widget.setColumnWidth(1, 100)
        self.ui.tree_widget.setColumnWidth(2, 100)
        self.ui.tree_widget.setColumnWidth(3, 1)
        self.ui.tree_widget.setColumnWidth(4, 200)
        
    def close_tab(self, index):
        if index > 1: # let's leave main tabs
            # let's store thread_ids in tabs' ObjectNames
            del self.open_threads[int(self.ui.tab_widget.currentWidget().objectName())]
            self.ui.tab_widget.removeTab(index);
        
    def update_threads(self):
        if not self.ui.get_forums_button.isEnabled():
            return
        logger.info('Updating threads...')
        self.ui.get_forums_button.setEnabled(0)
        self.forums_thread = QWorker(self)
        self.forums_thread.work('_update_threads')
        
    @QtCore.Slot(str)
    def on_finished(self, error):
        self.ui.get_forums_button.setEnabled(1)
        if error: logger.error(error)
        
    def on_tree_widget_item_changed(self, item, column):
        self._forum_cache[item.item_id].checked = checkstate_to_int(item.checkState(0))
        # TODO move color settings to config
        if self._forum_cache[item.item_id].subscribed: item.setBackground(0, QtGui.QColor(138, 43, 226))
        elif checkstate_to_int(item.checkState(0)): item.setBackground(0, QtGui.QColor(152, 251, 152))
        else: item.setBackground(0, QtGui.QColor(255, 255, 255))

    @QtCore.Slot(int, int, tuple, int)
    def add_tree_item(self, parent_id, item_id, item_data, level = 0):
        #pprint(self.ul_threads)
        if parent_id:
            parent = self.ul_threads[parent_id]
        else:
            parent = self.ui.tree_widget
            
        self.ui.tree_widget.itemChanged.disconnect(self.on_tree_widget_item_changed)
        if self.ul_threads.has_key(item_id):
            item = self.ul_threads[item_id]
        else:
            item = TreeWidgetItem(parent)
            item.item_id = item_id
            item.parent_id = parent_id
            
        threads = 0
        answers = 0
        timestamp = 0
        for column, value in item_data:
            item.setText(column, value)
            if column == 0: title = value
            elif column == 1: threads = value
            elif column == 2: answers = value
            elif column == 3:
                timestamp = value
                item.setText(4, datetime.fromtimestamp(int(timestamp)).strftime(DATE_TIME_FORMAT))
        checked = Qt.CheckState.Unchecked
        if self._forum_cache.has_key(item_id): checked = self._forum_cache[item_id].checked
        elif self._forum_cache.has_key(parent_id): checked = self._forum_cache[parent_id].checked
        item.setCheckState(0, int_to_checkstate(checked))
        # TODO move color settings to config
        if checked: item.setBackground(0, QtGui.QColor(152, 251, 152))
        subscribed = 0
        if self._forum_cache.has_key(item_id): subscribed = self._forum_cache[item_id].subscribed
        if subscribed: item.setBackground(0, QtGui.QColor(138, 43, 226))
        
        self.ul_threads[item_id] = item

        #if item_id not in self._forum_cache.keys():
        cache_item = Item({'item_id': item_id,
                                        'title': title,
                                        'parent_id': parent_id,
                                        'threads': threads,
                                        'answers': answers,
                                        'checked': checkstate_to_int(checked),
                                        'subscribed': subscribed,
                                        'level': level,
                                        'timestamp': timestamp,
                                        'date': datetime.fromtimestamp(int(timestamp)).strftime(DATE_TIME_FORMAT),
                                        })
        self._forum_cache[item_id] = cache_item
        self.ui.tree_widget.itemChanged.connect(self.on_tree_widget_item_changed)
        self.ui.tree_widget.sortItems(3, QtCore.Qt.SortOrder.DescendingOrder)
        
    @QtCore.Slot(int)
    def update_progress_bar(self, progress):
        self.ui.progressBar.setValue(progress)
        self.ui.progressBar.repaint()

    @QtCore.Slot(tuple)
    def update_status_bar(self, message):
        self.ui.statusbar.showMessage(message[0])
        self.ui.statusbar.repaint()

    def create_context_menu(self):
        self.popMenu = QtGui.QMenu(self)
        self.popMenu.addAction(u'Открыть', self.open_thread)
        self.popMenu.addSeparator()
        self.popMenu.addAction(u'Подписаться', self.subscribe)
        self.popMenu.addAction(u'Отписаться', self.unsubscribe)
        #self.popMenu.addSeparator()
        #self.popMenu.addAction(QtGui.QAction('something', self))    
        self.posts_popMenu = QtGui.QMenu(self)
        self.posts_popMenu.addAction(u'Игнорировать', self.ignore)
        
        self.subscribe_popMenu = QtGui.QMenu(self)
        self.subscribe_popMenu.addAction(u'Отписаться', self.unsubscribe1)
        
    def subscribe_context_menu(self, point):
        item = self.ui.subscribe_listWidget.itemAt(point)
        if item:
            self.subscribe_popMenu.exec_(self.ui.subscribe_listWidget.mapToGlobal(point))
        
    def tree_context_menu(self, point):
        item = self.ui.tree_widget.itemAt(point)
        if item and not item.childCount():
            self.popMenu.exec_(self.ui.tree_widget.mapToGlobal(point))
        
    def posts_list_context_menu(self, point):
        thread_id = int(self.ui.tab_widget.currentWidget().objectName())
        list_widget = self.open_threads[thread_id][0]
        item = list_widget.itemAt(point)
        if item:
            self.posts_popMenu.exec_(list_widget.mapToGlobal(point))
        
    def ignore(self):
        thread_id = int(self.ui.tab_widget.currentWidget().objectName())
        list_widget = self.open_threads[thread_id][0]
        user_id = list_widget.currentItem().user_id
        self.ignore_list.append(user_id)
        rows = range(list_widget.count())
        rows.reverse()
        for row in rows:
            item = list_widget.item(row)
            if item and item.user_id == user_id:
                list_widget.takeItem(row)
    
    def open_thread(self, thread_id = 0):
        if not thread_id in self._forum_cache.keys():
            thread_id = self.ui.tree_widget.currentItem().item_id
        if self._forum_cache[thread_id].level != THREAD:
            return
        posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = self.forum.get_posts_list(thread_id)
        t_title = unicode(unescape(t_title), FORUM_ENCODING)
        t_undertitle = unicode(unescape(t_undertitle), FORUM_ENCODING)
        tab = QtGui.QWidget()
        # let's store thread_ids in tabs' ObjectNames
        tab.setObjectName("%s" % thread_id)
        grid_layout_widget = QtGui.QWidget(tab)
        layout = QtGui.QGridLayout(grid_layout_widget)
        layout.setColumnStretch(1, 10)
        label = QtGui.QLabel()
        label.setText("%s %s" % (t_title, t_undertitle))
        layout.addWidget(label, 0, 0, 1, 2)
        listWidget = QtGui.QListWidget()
        listWidget.currentItemChanged.connect(self.view_post)
        for post in posts_list:
            if len(post) == 4:
                post_id, user, user_id, timestamp = post
            else:
                post_id, user, user_id, timestamp, avatar_url = post
            if user_id in self.ignore_list: continue
            item = QtGui.QListWidgetItem(unicode(user, FORUM_ENCODING))
            item.id = post_id
            item.thread_id = thread_id
            item.user_id = user_id
            listWidget.addItem(item)
        layout.addWidget(listWidget, 1, 0, 3, 1)
        view = QtWebKit.QWebView()
        path = os.getcwd()
        view.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile(path + "/css_2.css"))
        self.open_threads[thread_id] = (listWidget, view)
        layout.addWidget(view, 1, 1, 1, 1)
        textEdit = QtGui.QTextEdit(grid_layout_widget)
        layout.addWidget(textEdit, 2, 1, 1, 1)
        post_button = QtGui.QPushButton(u"Отправить")
        layout.addWidget(post_button, 3, 1, 1, 1)
        tab.setLayout(layout)
        listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        listWidget.customContextMenuRequested.connect(self.posts_list_context_menu)
        listWidget.setCurrentItem(item)
        index = self.ui.tab_widget.addTab(tab, t_title)
        self.ui.tab_widget.setCurrentIndex(index)
    
    def view_post(self, current, previous):
        post_id = current.id
        thread_id = current.thread_id
        listWidget, view = self.open_threads[thread_id]
        post = self.forum.get_posts(post_id)[0]
        HTML = unicode(post.post_text, FORUM_ENCODING)
        attach = ''
        if post.attach: attach = "%suploads/%s" % (SITE_URL, post.attach)
        HTML = """%s<br><img src="%s"><br><br><a href="%st/%s/p/%s" target="_blank">post's URL</a>      %s""" %\
                                        (HTML, attach, SITE_URL, thread_id, post_id, datetime.fromtimestamp(int(post.timestamp)).strftime(DATE_TIME_FORMAT))
        view.setTextSizeMultiplier(HTML_ZOOM_FACTOR)
        view.setHtml(HTML)
        
    def view_subscribed_post(self, current, previous):
        post_id = current.id
        thread_id = current.thread_id
        post = self.forum.get_posts(post_id)[0]
        HTML = unicode(post.post_text, FORUM_ENCODING)
        attach = ''
        if post.attach: attach = """<img src="%suploads/%s">""" % (SITE_URL, post.attach)
        HTML = """%s<br>%s<br><br><a href="%st/%s/p/%s" target="_blank">URL</a>      %s""" %\
                                        (HTML, attach, SITE_URL, thread_id, post_id, datetime.fromtimestamp(int(post.timestamp)).strftime(DATE_TIME_FORMAT))
        self.ui.subscribed_view.setTextSizeMultiplier(HTML_ZOOM_FACTOR)
        self.ui.subscribed_view.setHtml(HTML)
        
    def view_subscribed_thread(self, current, previous):
        self.ui.subscribe_listWidget11.currentItemChanged.connect(self.view_subscribed_post)
        self.ui.subscribe_listWidget11.currentItemChanged.disconnect(self.view_subscribed_post)
        self.ui.subscribe_listWidget11.set_items(self._subscribe_cache[current.item_id][2])
        self.ui.subscribe_listWidget11.currentItemChanged.connect(self.view_subscribed_post)
        
    def update_subscribed(self):
        for item_id, v in self._subscribe_cache.items():
            posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = self.forum.get_posts_list(item_id)
            text, last_post_id, posts = v
            for post in posts_list:
                post_id = post[0]
                user = post[1]
                user_id = post[2]
                if user_id in self.ignore_list: continue
                # TODO no need to process the whole list
                if post_id > last_post_id:
                    item = Item({'item_id': post_id,
                                                    'title': unicode(user, FORUM_ENCODING),
                                                    'parent_id': item_id,
                                })
                    posts.append(item)
            self._subscribe_cache[item_id] = [text, post_id, posts]
        
    def update_posts(self):
        for thread_id, value in self.open_threads.items():
            listWidget, web_view = value
            listWidget.currentItemChanged.disconnect(self.view_post)
            posts_list, t_title, f_id, unknown, unknown, t_answers, t_author, t_author_id, t_undertitle = self.forum.get_posts_list(thread_id)
            last_post_id = listWidget.item(listWidget.count() - 1).id
            for post in posts_list:
                post_id = post[0]
                user = post[1]
                user_id = post[2]
                if user_id in self.ignore_list: continue
                # TODO no need to process the whole list
                if post_id > last_post_id: 
                    item = QtGui.QListWidgetItem(unicode(user, FORUM_ENCODING))
                    item.id = post_id
                    item.thread_id = thread_id
                    listWidget.addItem(item)
                    
            listWidget.currentItemChanged.connect(self.view_post)
        
    def subscribe(self):
        item_id = self.ui.tree_widget.currentItem().item_id
        if self._subscribe_cache.has_key(item_id): return
        self._forum_cache[item_id].subscribed = 1
        item = self.ul_threads[item_id]
        item.setBackground(0, QtGui.QColor(138, 43, 226))
        
        subscribe_item = QtGui.QListWidgetItem(item.text(0))
        subscribe_item.item_id = item_id
        self.ui.subscribe_listWidget.addItem(subscribe_item)
        self._subscribe_cache[item_id] = (item.text(0), 0, [])
        
    def unsubscribe(self):
        item_id = self.ui.tree_widget.currentItem().item_id
        if not self._subscribe_cache.has_key(item_id): return
        self._forum_cache[item_id].subscribed = 0
        item = self.ul_threads[item_id]
        item.setBackground(0, QtGui.QColor(255, 255, 255))
        
        for item in self.ui.subscribe_listWidget.findItems(self._subscribe_cache[item_id][0], QtCore.Qt.MatchWildcard):
            self.ui.subscribe_listWidget.takeItem(self.ui.subscribe_listWidget.row(item))
        del self._subscribe_cache[item_id]

    def unsubscribe1(self):
        item_id = self.ui.subscribe_listWidget.currentItem().item_id
        if not self._subscribe_cache.has_key(item_id): return
        self._forum_cache[item_id].subscribed = 0
        item = self.ul_threads[item_id]
        item.setBackground(0, QtGui.QColor(255, 255, 255))
        
        for item in self.ui.subscribe_listWidget.findItems(self._subscribe_cache[item_id][0], QtCore.Qt.MatchWildcard):
            self.ui.subscribe_listWidget.takeItem(self.ui.subscribe_listWidget.row(item))
        del self._subscribe_cache[item_id]

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Escape:
            self.hide()
            
    def closeEvent(self, event):
        if self.ui.hide_to_tray_cb.checkState():
            self.write_settings()
            event.ignore()
            self.hide()
        else:
            quit_msg = "Are you sure you want to exit the program?"
            reply = QtGui.QMessageBox.question(self, 'Message', 
                            quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

            if reply == QtGui.QMessageBox.Yes:
                self.write_settings()
                event.accept()
            else:
                event.ignore()
            
    def change_interval(self):
        self.update_interval = self.ui.reload_interval_sb.value() * 1000 * 60
        self.forums_timer.stop()
        self.lcd_timer.timer.stop()
        self.lcd_timer.set_interval(self.update_interval)
        if self.update_interval:
            self.forums_timer.setInterval(self.update_interval)
            self.forums_timer.start()
            self.lcd_timer.timer.start(1000)
        self.settings.setValue("MainWindow/reload_interval_sb", self.ui.reload_interval_sb.value())
            
    def change_posts_interval(self):
        self.update_interval = self.ui.reload_posts_interval_sb.value() * 1000 * 60
        self.posts_timer.stop()
        self.lcd_posts_timer.timer.stop()
        self.lcd_posts_timer.set_interval(self.update_interval)
        if self.update_interval:
            self.posts_timer.setInterval(self.update_interval)
            self.posts_timer.start()
            self.lcd_posts_timer.timer.start(1000)
        self.settings.setValue("MainWindow/reload_posts_interval_sb", self.ui.reload_posts_interval_sb.value())
            
    def change_subscribed_update_interval(self):
        self.update_interval = self.ui.reload_interval_subscription_sb.value() * 1000 * 60
        self.subscribed_timer.stop()
        self.lcd_subscribed_timer.timer.stop()
        self.lcd_subscribed_timer.set_interval(self.update_interval)
        if self.update_interval:
            self.subscribed_timer.setInterval(self.update_interval)
            self.subscribed_timer.start()
            self.lcd_subscribed_timer.timer.start(1000)
        self.settings.setValue("MainWindow/reload_interval_subscription_sb", self.ui.reload_interval_subscription_sb.value())
            
    def init_subscribe_widget(self):
        for item_id, v in self._subscribe_cache.items():
            text, last_post_id, posts = v
            subscribe_item = QtGui.QListWidgetItem(text)
            subscribe_item.item_id = item_id
            self.ui.subscribe_listWidget.addItem(subscribe_item)
            
    def init_tree_widget(self):
        self.ui.tree_widget.setColumnCount(5)
        self.ui.tree_widget.setHeaderLabels([u'Форумы', u'Тем', u'Постов', u'', u'Дата'])   
        #pprint(self._forum_cache)
        for level in range(4):
            for key, value in self._forum_cache.iteritems():
                if value.level == level:
                    self.add_tree_item(value.parent_id, key, value._data(), level)
    
    def write_settings(self):
        logger.info('Writting settings')
        self.settings = QSettings(AUTHOR, APP_NAME)
        #self.settings = QSettings("settings.ini", QSettings.IniFormat)
        self.settings.beginGroup("MainWindow")
        self.settings.setValue("size", self.size())
        self.settings.setValue("pos", self.pos())
        self.settings.setValue("check_on_startup_cb", self.ui.check_on_startup_cb.checkState())
        self.settings.setValue("hide_to_tray_cb", self.ui.hide_to_tray_cb.checkState())
        self.settings.setValue("reload_interval_sb", self.ui.reload_interval_sb.value())
        self.settings.setValue("reload_posts_interval_sb", self.ui.reload_posts_interval_sb.value())
        self.settings.setValue("reload_interval_subscription_sb", self.ui.reload_interval_subscription_sb.value())
        self.settings.setValue("update_target", self.radio_button_group.checkedId())
        self.settings.endGroup()
        self.settings.setValue("_timestamp", self._bluetime)
        self.settings.setValue("_forum_cache", self._forum_cache)
        self.settings.setValue("_subscribe_cache", self._subscribe_cache)
        self.settings.setValue("_open_threads_list", self.open_threads.keys())
        self.settings.setValue("_ignore_list", self.ignore_list)

    def read_settings(self):
        self.settings = QSettings(AUTHOR, APP_NAME)
        #self.settings = QSettings("settings.ini", QSettings.IniFormat)
        self.settings.beginGroup("MainWindow")
        self.resize(self.settings.value("size", QSize(800, 600)))
        self.move(self.settings.value("pos", QPoint(200, 200)))
        self.ui.check_on_startup_cb.setCheckState(int_to_checkstate(self.settings.value("check_on_startup_cb", 0)))
        self.ui.hide_to_tray_cb.setCheckState(int_to_checkstate(self.settings.value("hide_to_tray_cb", 0)))
        self.ui.reload_interval_sb.setValue(int(self.settings.value("reload_interval_sb", 0)))
        self.ui.reload_posts_interval_sb.setValue(int(self.settings.value("reload_posts_interval_sb", 0)))
        self.ui.reload_interval_subscription_sb.setValue(int(self.settings.value("reload_interval_subscription_sb", 0)))
        self._update_target = int(self.settings.value("update_target", 0))
        self.radio_button_group.button(self._update_target).setChecked(1)
        self.settings.endGroup()        
        self._bluetime = self.settings.value("_timestamp", 0)
        self._forum_cache = self.settings.value("_forum_cache", {})
        self._subscribe_cache = self.settings.value("_subscribe_cache", {})
        self.open_threads_list = self.settings.value("_open_threads_list", [])
        self.ignore_list = self.settings.value("_ignore_list", [])
        if not self.ignore_list: self.ignore_list = [0]
        #pprint(self._forum_cache)
        if not self._forum_cache:
            self._forum_cache = {}
            for item_id, title in UL_THREADS.iteritems():
                item = Item({'title': title, 'item_id': item_id, 'level': TOP_LEVEL})
                self._forum_cache[item_id] = item

    def __icon_activated(self, reason):
        if reason == QtGui.QSystemTrayIcon.Trigger:
            if self.isActiveWindow():
                self.hide()
            else:
                self.show()
        
    
if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = Main()
    MainWindow.show()
    sys.exit(app.exec_())

